<template>
  <div>
      <s-table :search-params="searchParams" tree :COLUMNS="columns" :async-fc="page" ref="table">
          <template #tableHeader>
              <t-button @click="insert">新增信息</t-button>
              <t-button @click="onDelete" theme="warning">删除</t-button>
          </template>
      </s-table>
      <t-dialog v-model="modalOpen" @confirm="onModalSubmit" width="50%">
              <t-form ref="submitFormRef" labelAlign="top" :rules="FORM_RULES" :data="submitForm">
              <t-row style="width: 100%" :gutter="[10,24]">
                  <t-col :span="6">
                    <t-form-item :label="t('pages.sysPermission.type')" name="type">
                  <t-select v-model="submitForm.type" @change="chooseType" :options="typeOption" :placeholder="t('pages.sysPermission.typePlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col v-if="submitForm.type !== 2" :span="6">
                    <t-form-item :label="t('pages.sysPermission.path')" name="path">
                  <t-input v-model="submitForm.path"  :placeholder="t('pages.sysPermission.pathPlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col v-if="submitForm.type == 1 || submitForm.type == 2" :span="6">
                    <t-form-item :label="t('pages.sysPermission.parentId')" name="parentId">
                      <t-select v-model="submitForm.parentId" :options="parentOption" :placeholder="t('pages.sysPermission.parentIdPlaceholder')"/>
                    </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item :label="t('pages.sysPermission.name')" name="name">
                  <t-input v-model="submitForm.name" :placeholder="t('pages.sysPermission.namePlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item :label="t('pages.sysPermission.englishName')" name="englishName">
                  <t-input v-model="submitForm.englishName" :placeholder="t('pages.sysPermission.englishNamePlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col v-if="submitForm.type != 0" :span="6">
                    <t-form-item :label="t('pages.sysPermission.code')" name="code">
                  <t-input v-model="submitForm.code" :placeholder="t('pages.sysPermission.codePlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col v-if="submitForm.type != 2" :span="6">
                    <t-form-item :label="t('pages.sysPermission.outerChain')" name="outerChain">
                  <t-radio-group v-model="submitForm.outerChain" :options="outerChainOption" :placeholder="t('pages.sysPermission.outerChainPlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item :label="t('pages.sysPermission.icon')" name="icon">
                      <t-select
                      v-model="submitForm.icon"
                      :popup-props="{ overlayInnerStyle: { width: '430px' } }">
                      <t-option v-for="item in iconoption" :value="item.stem" :key="item.stem" style="display: inline-block; font-size: 20px">
                        <t-icon :name="item.stem" />
                      </t-option>
                      <template #valueDisplay>
                        <t-icon :name="submitForm.icon" :style="{ marginRight: '8px' }" />{{ submitForm.icon || t('pages.sysPermission.iconPlaceholder')}}
                      </template>
                    </t-select>
              </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item :label="t('pages.sysPermission.sort')" name="sort">
                  <t-input-number v-model="submitForm.sort" theme="column" style="width: 100%" :placeholder="t('pages.sysPermission.sortPlaceholder')"/>
              </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item :label="t('pages.sysPermission.remarks')" name="remarks">
                  <t-textarea v-model="submitForm.remarks" :placeholder="t('pages.sysPermission.remarksPlaceholder')"/>
              </t-form-item>
                  </t-col>
              </t-row>
          </t-form>
      </t-dialog>
  </div>
</template>
<script setup lang="ts">
/*****                                          引用部分开始                                          *****/
import { ref } from "vue";
import { t } from "@/locales";
import STable from '@/components/s-table/index.vue';
import { TableInstanceFunctions } from "@/components/s-table/type";
import { searchParams, COLUMNS, FORM_RULES,typeOption,outerChainOption } from "../sysPermission/props/index";
import { page, updateApi, insertApi, deleteById } from "@/api/sysPermission";
import { FormInstanceFunctions, Link, Space, MessagePlugin, DialogPlugin } from "tdesign-vue-next";
import { manifest } from 'tdesign-icons-vue-next'; // 获取全部图标的列表
import style from "@/config/style";
import { nextTick } from 'vue';
/*****                                          引用部分结束                                          *****/


/*****                                          属性定义部分开始                                          *****/
const submitForm = ref({
  id:null,
  path:null,
  type:null,
  parentId:null,
  name:null,
  englishName:null,
  code:null,
  outerChain:'0',
  icon:null,
  sort:null,
  remarks:null,
  
  //添加所用到的字段
});
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<TableInstanceFunctions>();
/*****                                          属性定义部分结束                                          *****/

//获取全部图标
const iconoption = ref(manifest);
const parentOption = ref([]);
const columns = COLUMNS.concat([{
  align: 'left',
  fixed: 'right',
  colKey: 'op',
  title: t('components.commonTable.operation'),
  cell: (h, slot:{row:any}) => h(Space, {}, [
      h(Link, {
          theme: 'primary',
          onClick: async() => {
            if (slot.row.type == 1) {
              await chooseType(1);
            }else if(slot.row.type == 2){
              await chooseType(2);  
            }
              submitForm.value = slot.row;
              modalOpen.value = true;
              
          }
      }, '修改'),
      h(Link, {
          theme: 'danger',
          onClick: () => {
              const confirmDialog = DialogPlugin.confirm({
                  header: `提示`,
                  body: `删除后，标记为${slot.row.id}的所有信息将被清空，且无法恢复`,
                  confirmBtn: {
                      content: '提交',
                      theme: 'primary',
                      loading: false,
                  },
                  theme: 'warning',
                  onConfirm: async () => {
                      confirmDialog.update({ confirmBtn: { content: '提交中', loading: true } });
                      await deleteById(slot.row.id);
                      MessagePlugin.success('删除成功！');
                      table.value.onSearch();
                      confirmDialog.update({ confirmBtn: { content: '提交', loading: false } });
                      confirmDialog.hide();
                  },
              })
          }
      }, '删除'),
  ])
}]);


/*****                                          页面方法开始                                          *****/
const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
  //配置默认值，但是也要把用到字段写出来
      id:null,
      path:null,
      type:null,
      parentId:null,
      name:null,
      englishName:null,
      code:null,
      outerChain:'0',
      icon:null,
      sort:null,
      remarks:null,
  };
  // 重置表单实例
  if (submitFormRef.value) {
     submitFormRef.value.reset();
}
 // 确保表单实例已经初始化
 nextTick(() => {
    if (submitFormRef.value) {
      submitFormRef.value.clearValidate();
    }
  });
}

const onDelete =async () => {
  
}

/**
* 提交表单
*/
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid === true) {
      if (submitForm.value.id) {
        await updateApi(submitForm.value);
        MessagePlugin.success('修改成功！');
        table.value.onSearch();
      } else {
        await insertApi(submitForm.value);
        MessagePlugin.success('新增成功！');
        table.value.onSearch();
      }

      // 关闭弹出框
      modalOpen.value = false;
      // 使用 nextTick 确保数据更新后界面能够及时刷新
      await nextTick();
      // 重新加载数据
      table.value.onSearch();
    
  }
}

const chooseType = async (value: any) => {
  if (value == 1) {
      const { records } = await page({ pageNo: 1, pageSize: 99, params: { type: 0 } });
      parentOption.value = records.map((i: any) => ({ label: i.name, value: i.id }));
  } else if (value == 2) {
      const { records } = await page({ pageNo: 1, pageSize: 99, params: { type: 1 } });
      parentOption.value = records.map((i: any) => ({ label: i.name, value: i.id }));
  }
}


/*****                                          页面方法结束                                          *****/
</script>